package org.goodprinciples.oracolo.dao.impl;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Properties;
import javax.sql.DataSource;
import org.goodprinciples.commons.dao.GenericDAO;
import org.goodprinciples.oracolo.exception.OracoloRuntimeException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

/**
 *
 * @author Francesco Conte
 */
public abstract class JdbcSpringGenericDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {
    
    public static final String FIND_BY_ID = "findById";
    public static final String FIND_ALL = "findAll";
    public static final String FIND_BY_EXAMPLE = "findByExample";
    public static final String MAKE_PERSISTENT = "makePersistent";
    public static final String SYNCHRONIZE = "synchronize";
    public static final String MAKE_TRANSIENT = "makeTransient";
    
    private static final String FILTER_PREFIX = "filter.";
    private static final String QUERY_PREFIX = "query.";
    
    private Properties properties = null;
    private NamedParameterJdbcTemplate jdbcTemplate = null;
    
    public void setProperties(Properties properties) {
        this.properties = new Properties();
        Iterator<?> iterator = properties.keySet().iterator();
        while(iterator.hasNext()) {
            Object key = iterator.next();
            if(key instanceof String) {
                String sKey = (String) key;
                this.properties.put(sKey.toLowerCase(), properties.getProperty(sKey));
            }
        }
    }
    
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    }
    
    protected NamedParameterJdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
    
    protected String getQuery(String queryId) {
        StringBuilder builder = new StringBuilder(QUERY_PREFIX);
        builder.append(queryId);
        String query = properties.getProperty(builder.toString().toLowerCase());
        if(query == null) {
            throw new OracoloRuntimeException("Cannot find query: "+builder.toString());
        }
        return query;
    }
    
    protected String getFilter(String filterId) {
        StringBuilder builder = new StringBuilder(FILTER_PREFIX);
        builder.append(filterId);
        String filter = properties.getProperty(builder.toString().toLowerCase());
        if(filter == null) {
            throw new OracoloRuntimeException("Cannot find filter: "+builder.toString());
        }
        return filter;
    }
    
}
